<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\shopro\trade\Order as TradeOrderModel;
use app\admin\model\shopro\Coupon;
use app\admin\model\shopro\user\Coupon as UserCouponModel;
use think\Db;

header("Content-type: text/html; charset=utf-8");
include 'HttpClient.php';

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        
        
        $this->success('请求成功');
    }
    
    public function shopPrint(){
        $order = Db::name('shopro_order')->where(['is_dy'=>0,'status'=>'paid'])->select();
        
        if($order){
            foreach($order as $k=>$v){
                //获取商品
                $items = Db::name('shopro_order_item')
                        ->alias('i')
                        ->join('shopro_goods g','g.id=i.goods_id','left')
                        ->field('i.*,g.category_ids')
                        ->where(['order_id'=>$v['id']])
                        ->select();
                      
                $catearr = [];
                $nocate = [];
                foreach($items as $kx=>$vx){
                    //目前只考虑单个的 和二级
                    if($vx['category_ids']){
                        $cate = Db::name('shopro_category')->where(['id'=>$vx['category_ids']])->find();
                        $catetop = Db::name('shopro_category')->where(['id'=>$cate['parent_id']])->find();
                        $catename = $catetop['name'] . ' - ' . $cate['name'];
                        $iscz = -1;
                        foreach($catearr as $ck=>$cv){
                            if($cv['name'] == $catename){
                                $iscz = $ck;
                            }
                        }
                        
                        if($iscz>=0){
                            $catearr[$iscz]['items'][] = $vx;
                        }else{
                            
                            $data = [];
                            $data['name'] = $catename;
                            $data['print_sn'] = $cate['shop_print'];
                            $data['items'][] = $vx;
                            $catearr[] = $data;
                        }
                    }else{
                        $nocate[] = $vx;
                    }
                }
                $snarr[0] = '922607923';
                $content = '';
                $content = '<CB>慢生活校园商城</CB><BR>';
                $content .= '订单号：'.$v['order_sn'].'<BR>';
                $content .= '名称　　　　　 单价  数量 金额<BR>';
                $content .= '--------------------------------<BR>';
                //整理items
                foreach($catearr as $ck=>$cv){
                    if($cv['print_sn']){
                        $snarr[] = $cv['print_sn'];
                    }
                    $content .= '<BOLD>--'.$cv['name'].'--</BOLD><BR>';
                    foreach($cv['items'] as $kk2=>$vv2){
                        $content .= $vv2['goods_title'].'<BR>';
                        $content .= '<RIGHT>'.$vv2['goods_sku_text'].'</RIGHT><BR>';
                        $content .= '　　　　　　 　 '.$vv2['goods_price'].'  x'.$vv2['goods_num'].'  '.$vv2['pay_fee'].'<BR>';
                    }
                }
                if($nocate){
                    $content .= '<BOLD>--其他分类--</BOLD><BR>';
                    foreach($nocate as $kk3=>$vv3){
                        $content .= $vv3['goods_title'].'<BR>';
                        $content .= '<RIGHT>'.$vv3['goods_sku_text'].'</RIGHT><BR>';
                        $content .= '　　　　　　 　 '.$vv3['goods_price'].'  x'.$vv3['goods_num'].'  '.$vv3['pay_fee'].'<BR>';
                    }
                }
                
                // $content .= '<QR></QR>';
                // $content .= '<QR>http://www.feieyun.com</QR>';
                // p($content);die;
                
                // p($content);die;
                $content .= '--------------------------------<BR>';
                $content .= '备注：'.$v['remark'].'<BR>';
                if($v['upstair']){
                    $content .= '<BOLD>上楼费：'.$v['upstair'].'元</BOLD><BR>';
                }
                $content .= '配送费：'.$v['dispatch_amount'].'元<BR>';
                if($v['coupon_discount_fee']>0){
                    $content .= '优惠券：-'.$v['coupon_discount_fee'].'元<BR>';
                }
                if($v['total_discount_fee']>0){
                    $content .= '优惠总金额：-'.$v['total_discount_fee'].'元<BR>';
                }
                
                // $content .= '配送费：'.$v['dispatch_amount'].'元<BR>';
                $content .= '合计：'.$v['pay_fee'].'元<BR>';
                $paotui= Db::name('paotui_post')->where(['shopro_order_id'=>$v['id']])->find();
                if($paotui){
                    $content .= '--------------------------------<BR>';
                    $content .= '送货地点：'.$paotui['to_province'].$paotui['to_city'].$paotui['to_district'].'<BR>';
                    
                    $content .= '<BOLD>学校地址：'. $paotui['school_name'].' '.$paotui['build_name'].'</BOLD><BR>';
                    $content .= '<BOLD>具体地址：'. $paotui['to_poi'].' '.$paotui['to_address'].'</BOLD><BR>';
                    $content .= '<BOLD>下单人：'.$paotui['to_name'].'</BOLD><BR>';
                    $content .= '<BOLD>联系电话：'.$paotui['to_mobile'].'</BOLD><BR>';
                }else{
                    //如果没有生成商城订单，直接调取shopro里的订单
                    $address = Db::name('shopro_order_address')->where('order_id',$v['id'])->find();
                    $content .= '--------------------------------<BR>';
                    $content .= '送货地点：'.$address['province_name'].$address['city_name'].$address['district_name'].'<BR>';
                    
                    $content .= '<BOLD>学校地址：'. $address['school_name'].' '.$address['build_name'].'</BOLD><BR>';
                    $content .= '<BOLD>具体地址：'.$address['address'].'</BOLD><BR>';
                    $content .= '<BOLD>下单人：'.$address['consignee'].'</BOLD><BR>';
                    $content .= '<BOLD>联系电话：'.$address['mobile'].'</BOLD><BR>';
                }
                
                $content .= '下单时间：'.date('Y-m-d H:i:s',$v['createtime']).'<BR>';
                // p($content);die;
                foreach($snarr as $skk=>$svv){
                    
                    $res = $this->printMsg($content,$svv);
                }
                Db::name('shopro_order')->where(['id'=>$v['id']])->update(['is_dy'=>1,'updatetime'=>time()]);
            }
        }
    } 
    public function shopPrintId($id){
        
        $order = Db::name('shopro_order')->where(['id'=>$id])->select();
        
        if($order){
            foreach($order as $k=>$v){
                //获取商品
                $items = Db::name('shopro_order_item')
                        ->alias('i')
                        ->join('shopro_goods g','g.id=i.goods_id','left')
                        ->field('i.*,g.category_ids')
                        ->where(['order_id'=>$v['id']])
                        ->select();
                      
                $catearr = [];
                $nocate = [];
                foreach($items as $kx=>$vx){
                    //目前只考虑单个的 和二级
                    if($vx['category_ids']){
                        $cate = Db::name('shopro_category')->where(['id'=>$vx['category_ids']])->find();
                        $catetop = Db::name('shopro_category')->where(['id'=>$cate['parent_id']])->find();
                        $catename = $catetop['name'] . ' - ' . $cate['name'];
                        $iscz = -1;
                        foreach($catearr as $ck=>$cv){
                            if($cv['name'] == $catename){
                                $iscz = $ck;
                            }
                        }
                        
                        if($iscz>=0){
                            $catearr[$iscz]['items'][] = $vx;
                        }else{
                            
                            $data = [];
                            $data['name'] = $catename;
                            $data['print_sn'] = $cate['shop_print'];
                            $data['items'][] = $vx;
                            $catearr[] = $data;
                        }
                    }else{
                        $nocate[] = $vx;
                    }
                }
                $snarr[0] = '922607923';
                $content = '';
                $content = '<CB>慢生活校园商城</CB><BR>';
                $content .= '订单号：'.$v['order_sn'].'<BR>';
                $content .= '名称　　　　　 单价  数量 金额<BR>';
                $content .= '--------------------------------<BR>';
                //整理items
                foreach($catearr as $ck=>$cv){
                    if($cv['print_sn']){
                        $snarr[] = $cv['print_sn'];
                    }
                    $content .= '<BOLD>--'.$cv['name'].'--</BOLD><BR>';
                    foreach($cv['items'] as $kk2=>$vv2){
                        $content .= $vv2['goods_title'].'<BR>';
                        $content .= '<RIGHT>'.$vv2['goods_sku_text'].'</RIGHT><BR>';
                        $content .= '　　　　　　 　 '.$vv2['goods_price'].'  x'.$vv2['goods_num'].'  '.$vv2['pay_fee'].'<BR>';
                    }
                }
                if($nocate){
                    $content .= '<BOLD>--其他分类--</BOLD><BR>';
                    foreach($nocate as $kk3=>$vv3){
                        $content .= $vv3['goods_title'].'<BR>';
                        $content .= '<RIGHT>'.$vv3['goods_sku_text'].'</RIGHT><BR>';
                        $content .= '　　　　　　 　 '.$vv3['goods_price'].'  x'.$vv3['goods_num'].'  '.$vv3['pay_fee'].'<BR>';
                    }
                }
                
                // $content .= '<QR></QR>';
                // $content .= '<QR>http://www.feieyun.com</QR>';
                // p($content);die;
                
                // p($content);die;
                $content .= '--------------------------------<BR>';
                $content .= '备注：'.$v['remark'].'<BR>';
                if($v['upstair']){
                    $content .= '<BOLD>上楼费：'.$v['upstair'].'元</BOLD><BR>';
                }
                $content .= '配送费：'.$v['dispatch_amount'].'元<BR>';
                if($v['coupon_discount_fee']>0){
                    $content .= '优惠券：-'.$v['coupon_discount_fee'].'元<BR>';
                }
                if($v['total_discount_fee']>0){
                    $content .= '优惠总金额：-'.$v['total_discount_fee'].'元<BR>';
                }
                
                // $content .= '配送费：'.$v['dispatch_amount'].'元<BR>';
                $content .= '合计：'.$v['pay_fee'].'元<BR>';
                $paotui= Db::name('paotui_post')->where(['shopro_order_id'=>$v['id']])->find();
                if($paotui){
                    $content .= '--------------------------------<BR>';
                    $content .= '送货地点：'.$paotui['to_province'].$paotui['to_city'].$paotui['to_district'].'<BR>';
                    
                    $content .= '<BOLD>学校地址：'. $paotui['school_name'].' '.$paotui['build_name'].'</BOLD><BR>';
                    $content .= '<BOLD>具体地址：'. $paotui['to_poi'].' '.$paotui['to_address'].'</BOLD><BR>';
                    $content .= '<BOLD>下单人：'.$paotui['to_name'].'</BOLD><BR>';
                    $content .= '<BOLD>联系电话：'.$paotui['to_mobile'].'</BOLD><BR>';
                }else{
                    //如果没有生成商城订单，直接调取shopro里的订单
                    $address = Db::name('shopro_order_address')->where('order_id',$v['id'])->find();
                    $content .= '--------------------------------<BR>';
                    $content .= '送货地点：'.$address['province_name'].$address['city_name'].$address['district_name'].'<BR>';
                    
                    $content .= '<BOLD>学校地址：'. $address['school_name'].' '.$address['build_name'].'</BOLD><BR>';
                    $content .= '<BOLD>具体地址：'.$address['address'].'</BOLD><BR>';
                    $content .= '<BOLD>下单人：'.$address['consignee'].'</BOLD><BR>';
                    $content .= '<BOLD>联系电话：'.$address['mobile'].'</BOLD><BR>';
                }
                
                $content .= '下单时间：'.date('Y-m-d H:i:s',$v['createtime']).'<BR>';
                // p($content);die;
                foreach($snarr as $skk=>$svv){
                    $res = $this->printMsg($content,$svv);
                }
                Db::name('shopro_order')->where(['id'=>$v['id']])->update(['is_dy'=>1,'updatetime'=>time()]);
                $this->success('打印成功');
            }
        }
    } 
    
    function printMsg($content,$sn){
        //根据sn码查询user和key
        $res = Db::name('printinfo')->where(['sn'=>$sn])->find();
    
        $user = $res['user'];
        $ukey = $res['ukey'];
        
        $time = time();         //请求时间
        $msgInfo = array(
          'user'=>$user,
          'stime'=>$time,
          'sig'=>$this->signature($user,$ukey,$time),
          'apiname'=>'Open_printMsg',
          'sn'=>$sn,
          'content'=>$content,
          'times'=>2//打印次数
        );
        
        $IP='api.feieyun.cn';      //接口IP或域名
        $PORT=80;            //接口IP端口
        $PATH='/Api/Open/';    //接口路径
        
        $client = new HttpClient($IP,$PORT);
        
        if(!$client->post($PATH,$msgInfo)){
            echo 'error';
        }else{
          //服务器返回的JSON字符串，建议要当做日志记录起来
            $result = $client->getContent();
            echo $result;
        }
    }
    function signature($user,$ukey,$time){
        return sha1($user.$ukey.$time);//公共参数，请求公钥
    }
    /**
     * 支付测试
     *
     */
    public function testpay()
    {
		$torder=TradeOrderModel::where('id',21)->find();
		if($torder['type']=="vip"){
			$ext = $torder['ext'];
			$rule = $ext['rule'] ?? [];
			$user=auth_user();
			$cids = explode(',',$rule['coupon_ids']);
			foreach($cids as $id){
				$coupon = Coupon::normal()      // 正常的可以展示的优惠券
					->canGet()      // 在领取时间之内的
					->lock(true)
					->where('id', $id)
					->find();
				if (!$coupon) {
					error_stop('优惠券未找到');
				}
				$this->send($user, $coupon);
			}
			
			$days=$rule['days'];
			
			if ($days > 0) {
				$nowdate=$user['vipend'] && $user['vipend']!='0000-00-00'?$user['vipend']:date('Y-m-d');
				$afterdate=date('Y-m-d',strtotime($nowdate)+$days*86400);
				db('user')->update(['id'=>$user['id'],'vipend'=>$afterdate,'updatetime'=>time()]);
			}
		}
    }
    /**
     * 发放优惠券
     *
     * @param array|object $user 发放用户
     * @param array|object $coupon 要发放的优惠券
     * @param integer ucid 关联用户优惠券 //masks 新增 
     * @return array|object
     */
    private function send($user, $coupon, $ucid=0) {
        if ($coupon->get_status == 'cannot_get') {
            error_stop('您已经领取过了');
        }

        if ($coupon->stock <= 0) {
            error_stop('优惠券已经被领完了');
        }

        $coupon->setDec('stock');

        $userCoupon = new UserCouponModel();
        $userCoupon->user_id = $user->id;
        $userCoupon->coupon_id = $coupon->id;
        $userCoupon->use_time = null;
		if($ucid){
			$userCoupon->isact=0;
			$userCoupon->ucid=$ucid;
		}
        $userCoupon->save();

        return $userCoupon;
    }

}
